/*
 * ConversionDAO.java
 *
 * Created on March 28, 2007, 10:07 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package edu.byu.isys413.samlam;

import java.sql.*;
import java.util.LinkedList;
import java.util.List;
/**
 * Extends the RevenueSourceDAO and handles database interaction for Conversion revenue source objects
 * @author Sam
 */
public class ConversionDAO extends RevenueSourceDAO{
    
    private static ConversionDAO instance;
    /** Creates a new instance of ConversionDAO */
    private ConversionDAO() {
    }
    
    public static synchronized ConversionDAO getInstance() {
        if (instance == null) {
            instance = new ConversionDAO();
        }
        return instance;
    }
    
    /////////////////////////////////
    ///   CREATE
    
    /**
     * There's no need for two creates because we don't need
     * a connection to create BOs.  We run the insert statement
     * later, when it get's saved for the first time.
     */
    public Conversion create() {
        Conversion conversion = null;
        try{
            String id = GUID.generate();
            conversion = new Conversion(id);
            Cache cache = Cache.getInstance();
            cache.put(conversion.getId(), conversion);
            
        }catch(Exception e){
            e.printStackTrace();
        }
        return (Conversion)conversion;
    }
    
    
    /////////////////////////////////////
    ///   READ
    
    /**
     * This is the public read statement.  It loads an existing record
     * from the database.
     */
    public synchronized Conversion read(String id) throws DataException {
        // check to see if id in the cache
        Conversion conversion = (Conversion)Cache.getInstance().get(id);
        if(conversion != null){
            // if so, return it immediately
            return (Conversion)conversion;
        }
        
        
        
        Connection conn = null;
        try {
            // retrieve a database connection from the pool
            conn = ConnectionPool.getInstance().get();
            // call read with a connection (the other read method in this class)
            conversion = ConversionDAO.getInstance().read(id, conn);
            
            // release the connection
            conn.commit();
            ConnectionPool.getInstance().release(conn);
            
        }catch (ConnectionPoolException e4){
            throw new DataException("Could not get a connection to the database.");
            
        }catch (SQLException e) {
            // rollback
            try{
                conn.rollback();
                ConnectionPool.getInstance().release(conn);
            }catch(SQLException e2){
                throw new DataException("Big error: could not even release the connection", e2);
            }catch (ConnectionPoolException e3){
                throw new DataException("Could not get a connection to the database.");
                
            }
            throw new DataException("Could not retrieve record for id=" + id, e);
        }
        
        // return object
        return conversion;
    }
    
    /**
     *  This is a package method that is called by the public read (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection objects or SQLExceptions.
     */
    public synchronized Conversion read(String id, Connection conn) throws SQLException, DataException {
        // check again if the id is in the cache, and if so,
        // just get it from the cache.  we need to check again
        // because this method might be called directly from
        // another DAO rather than from read above.
        Conversion conversion = (Conversion)Cache.getInstance().get(id);
        if(conversion != null){
            return conversion;
        }
        // if not in the cache, get a result set from
        // a SELECT * FROM table WHERE id=guid
        //query the database
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM conversion WHERE conversionid = '"+ id + "'");
        
        
        if (rs.next()) {
        //call sets from the result set
        conversion.setId(rs.getString("id"));
        Cache.getInstance().put(conversion.getId(), conversion);
        super.read(conversion.getId(), conn);
        
        conversion.setObjectAlreadyInDB(true);
        
        
        // save to the cache
        Cache.getInstance().touch(conversion.getId());
        stmt.close();
        }else{
            throw new DataException("Object was not found in the database.");
            
        }
        // return the BO
        return conversion;
    }
    
    //////////////////////////////////
    ///   UPDATE
    
    /**
     * This is the public save method.  It is what is called when
     * the user (controller) code wants to save or update an object
     * into the database.
     */
    public synchronized void save(RevenueSource conversion) throws DataException {
        Connection conn = null;
        try {
            // retrieve a database connection from the pool
            conn = ConnectionPool.getInstance().get();
            // call save with a connection (the other save method in this class)
            this.save((Conversion)conversion, conn);
            // release the connection
            conn.commit();
            ConnectionPool.getInstance().release(conn);
        }catch (ConnectionPoolException e4){
            throw new DataException("Could not get a connection to the database.");
        }catch (SQLException e) {
            // rollback
            try {
                conn.rollback();
                ConnectionPool.getInstance().release(conn);
            }catch (ConnectionPoolException e4){
                throw new DataException("Could not get a connection to the database.");
            }catch (SQLException e2) {
                throw new DataException("Big error: could not even release the connection", e2);
            }
            
            throw new DataException("Could not retrieve record for id=" + conversion.getId(), e);
        }
    }
    
    
    /**
     *  This is a package method that is called by the public save (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection objects or SQLExceptions.
     *
     *  By having other DAOs call this save method (rather than update or
     *  insert below, each DAO in a chained save (like the ConversionDAO calling
     *  MembershipDAO calling InterestDAO save chain) can independently decide
     *  whether to udpate or insert the BO it's saving.  That's why I made
     *  update and insert private rather than package level -- if you call
     *  them directly from another DAO, this DAO can't decide whether it's
     *  object needs to be inserted or updated.
     */
    synchronized void save(Conversion conversion, Connection conn) throws SQLException, DataException {
        // check the dirty flag in the object.  if it is dirty,
        // run update or insert
        if (conversion.isDirty()) {
            
            if (conversion.isObjectAlreadyInDB() == true) {
                update(conversion, conn);
            }else{
                insert(conversion, conn);
            }
            super.save(conversion, conn);
            // set the dirty flag to false now that we've saved it
            conversion.setDirty(false);
            
        }
        
        // touch the cache for the object
        Cache.getInstance().touch(conversion.getId());
    }
    
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL udpate statement and make it more readable.  But
     * logically, it's really just a part of save.
     */
    private synchronized void update(Conversion conversion, Connection conn) throws SQLException, DataException {
        // do the update statement
        Statement stmt = conn.createStatement();
        //stmt.executeUpdate("UPDATE conversion set conversionid='"+conversion.getId()+"', numinset="+conversion.getNumInSet()+", papertype='"+conversion.getPaperType()+"', photodescpription='"+conversion.getPhotoDescription() +"', phototype='" + conversion.getPhotoType() + "', quantity = " + conversion.getQuantity() + ", size='" + conversion.getSize() + "', unitprice=" + conversion.getUnitPrice());
        stmt.close();
    }
    
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL insert statement and make it more readable.  But
     * logically, it's really just a part of save.
     */
    private synchronized void insert(Conversion conversion, Connection conn) throws SQLException, DataException {
        // do the insert SQL statement
        Statement stmt = conn.createStatement();
        //stmt.executeUpdate("INSERT INTO conversion VALUES ('" + conversion.getId()+"', "+conversion.getNumInSet()+", '"+conversion.getPaperType()+"', '"+conversion.getPhotoDescription() +"', '" + conversion.getPhotoType() + "', " + conversion.getQuantity() + ", '" + conversion.getSize() + "', " + conversion.getUnitPrice() + ")");
        stmt.close();
        // tell the object that it's now in the db (so we call update next time not insert)
        conversion.setObjectAlreadyInDB(true);
    }
    
    
    ////////////////////////////////////
    ///   DELETE
    // we are not supporting because we never want to delete the conversion from
    // our database.
    
    
    
    //////////////////////////////
    ///  SEARCH methods
}
    
